<template>
  <div>
    <el-dialog :title="title" :visible.sync="detailvisible" width="90%" append-to-body class="my-dialog" @close="cancel"
               :close-on-click-modal="false">
      <div>
        <div class="scheduling-top">
          <div class="scheduling-header">
            <div class="scheduling-header-name">
              班次说明:
            </div>
            <div class="scheduling-header-list" v-if="SignCatelist">
              <div class="scheduling-header-list-line" v-for="(item, index) in SignCatelist"
                   :style="{'background': item.color}">
                <div v-if="item.id">
                  {{ item.name }}
<!--                  {{-->
<!--                    `${item.startTime1}-${item.endNext1 ? '次日' : ''}${item.endTime1} ${item.startNext2 ? '次日' : ''}${item.startTime2}${item.startTime2 ? '-' : ''}${item.endNext2 ? '次日' : ''}${item.endTime2}`-->
<!--                  }}-->
                  {{
                    `${item.comeTime1}-${item.outNext1?'次日':''}${item.outTime1} ${item.comeTime2&&item.comeNext2?'次日':''}${item.comeTime2 || ''}${item.comeTime2?'-':''}${item.outTime2&&item.outNext2?'次日':''}${item.outTime2 || ''}`
                  }}
                </div>
                <div v-else class="scheduling-header-list-type">
                  {{ item.name }}
                </div>
              </div>
            </div>
            <div v-else>
              暂无班次信息
            </div>
          </div>
        </div>
        <div v-if="teamlist.length">
          <div class="scheduling-top-time">
            <el-date-picker
              v-model="monthThis"
              size="small"
              type="month"
              format="yyyy-MM"
              value-format="yyyy-MM"
              @change="monthThisFn()"
              placeholder="选择月">
            </el-date-picker>
          </div>
          <div class="table-scheduling">
            <div :style="{'width': widthTable+'px'}" class="table-inbody">
              <div class="table-scheduling-time table-scheduling-header">
                <div class="table-scheduling-time-list">
                  姓名
                </div>
                <div class="table-scheduling-time-list-td table-scheduling-time-list-td-day"
                     v-for="(item, index) in dayMonth">
                  <span class="day">{{ index + 1 }}</span>
                  <span class="week">{{ item.week }}</span>
                </div>
              </div>
              <!--              团队人员-->
              <div class="table-scheduling-time table-scheduling-list" v-for="(item, index) in teamlist">
                <div class="table-scheduling-time-list">
                  {{ item.nickName }}
                </div>
                <!--                每月天数-->
                <div class="table-scheduling-time-list-td popover-box-td" v-for="(day_, day_index) in dayMonth" :style="{'background': monthScheduList&&monthScheduList[item.id]?(monthScheduList[item.id][day_.dayName]?SignCatelist[monthScheduList[item.id][day_.dayName].cateId].color
                      :''):'' ,'color': monthScheduList&&monthScheduList[item.id]&&monthScheduList[item.id][day_.dayName]?'#fff': ''}">
                  <el-popover
                    class="popoverLine"
                    placement="right"
                    :ref="`myPopver${item.id}-${day_.dayName}`"
                    width="200"
                    trigger="click">
                    <div class="popover-body">
                      <div class="popover-title">
                        编辑该员工当天班次
                      </div>
                      <div class="popover-box-title-list" v-for="(item_c, index_C) in SignCatelist"
                           :style="{'background': item_c.color}" @click="workLine(item, day_, item_c)"
                           :class="{'popover-box-rest': !item_c.id}">
                        {{ item_c.name }}
                      </div>
                      <div class="popover-box-title-list popover-box-clear" @click="clearDayScheduling(item, day_)"
                           v-if="monthScheduList&&monthScheduList[item.id]&&monthScheduList[item.id][day_.dayName]">
                        清除
                      </div>
                    </div>
                    <span slot="reference" class="button-scheduling">{{
                        monthScheduList && monthScheduList[item.id] ? (monthScheduList[item.id][day_.dayName] ? SignCatelist[monthScheduList[item.id][day_.dayName].cateId].name
                          : '') : ''
                      }}</span>
                  </el-popover>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div v-else class="notdata">
          未找到可分配班次人员，请添加驻点人员
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel" size="small">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listStagnationPointUser} from "@/api/system/stagnation_point";
import {listSignCate, listScheduling, addScheduling, updateScheduling, delScheduling} from "@/api/system/sign_category";

export default {
  name: "index",
  props: ['visible', 'param'], // param 执勤点信息
  components: {},
  data() {
    return {
      teamlist: [],
      detailvisible: false,
      title: '排班管理',
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      teamUserVisible: false,
      color: ['#457eca', '#ad6acd', '#ad6acd'],
      value2: '',
      widthTable: 0,
      SignCatelist: null,
      dayMonth: [],
      monthThis: '',
      monthScheduList: null,
      flagTime: true, // 防止频繁点击
    }
  },
  watch: {
    visible() {
      this.detailvisible = this.visible
      if (this.visible) {
        console.log('执勤点信息', this.param)
        this.queryParams.pointsId = this.param.id
        this.getList()
        this.getUserList()
        let tiem_ = this.newDate().split('-')
        this.monthThis = tiem_.join('-')
        this.getDaysOfWeek(tiem_[0], tiem_[1])
      } else {
        this.flagTime = true
        this.SignCatelist = null
        this.dayMonth = []
        this.monthThis = ''
        this.monthScheduList = null
      }
    }
  },
  created() {
  },
  methods: {
    // 清除用户当天排班
    clearDayScheduling(user, day_) {
      let id_ = this.monthScheduList[user.id][day_.dayName].id
      delScheduling(id_).then(res => {
        let user_ = JSON.parse(JSON.stringify(this.monthScheduList[user.id]))
        delete user_[day_.dayName]
        this.$set(this.monthScheduList, user.id, user_)
      })
    },
    // 手动分配班次
    workLine(user, day_, schedul) {
      console.log('分配班次', user, day_, schedul)
      console.log('this.monthScheduList', this.monthScheduList)
      // user 用户 day_ 日期时间 schedul 排班类型
      if (!this.flagTime) {
        return
      }
      this.flagTime = false
      // 班次
      if (this.monthScheduList && this.monthScheduList[user.id][day_.dayName]) {
        let data_ = {
          id: this.monthScheduList[user.id][day_.dayName].id,
          cateId: 0
        }
        if (schedul.id) {
          data_.cateId = schedul.id
        }
        updateScheduling(data_).then(res => {
          let user_ = JSON.parse(JSON.stringify(this.monthScheduList[user.id]))
          user_[day_.dayName].cateId = data_.cateId
          this.$set(this.monthScheduList, user.id, user_)
          this.flagTime = true
        })
      } else {
        let data_ = {
          cateId: 0, // 考勤方案id
          userId: user.id, // 用户id
          month: this.monthThis.split('-').join(''), // 月份
          day: day_.dayName, // 日期
          projectId: this.param.projectId, //项目id
          pointsId: this.param.id, //驻点id
        }
        if (schedul.id) {
          data_.cateId = schedul.id
        }
        addScheduling(data_).then(res => {
          // 刷新页面，更新当前用户的排班记录
          this.listSchedulingFn(user.id)
        })
      }
    },
    // 获取每个人的排班
    listSchedulingFn(userId) {
      //   cateId:'', // 考勤方案id
      //   deptId:'', //项目id
      //   userId:'', //用户id
      //   month:'', // 月份
      //   day:'', //日期
      //   pointsId 驻点
      let data_ = {
        pageNum: 1,
        pageSize: 3000,
        pointsId: this.param.id, //  驻点
        month: this.monthThis.split('-').join(''), // 月份
      }
      if (userId) {
        data_.userId = userId
      }
      listScheduling(data_).then(res => {
        // userId day
        let user_ = {}
        for (let item of res.rows) {
          if (!user_[item.userId]) {
            user_[item.userId] = {}
          }
          user_[item.userId][item.day] = item
        }
        this.monthScheduList = JSON.stringify(user_)!=='{}'?user_:null
        this.flagTime = true
        // 需要将数据分配给各个用户身上
      })
    },
    /** 班次 */
    getList() {
      this.loading = true;
      listSignCate(this.queryParams).then(response => {
        if (response.rows.length) {
          let list_ = {}
          for (let index in response.rows) {
            let item = response.rows[index]
            item.color = this.color[index]
            list_[item.id] = item
          }
          list_[0] = {
            id: 0,
            name: '休息',
            color: '#ddd'
          }
          this.SignCatelist = list_;
        }
      });
    },
    /** 多人团队人员 */
    getUserList() {
      this.loading = true;
      listStagnationPointUser({
        pageNum: 1,
        pageSize: 200,
        pointsId: this.param.id, //  驻点
      }).then(response => {
        for (let item of response.rows) {
          item.dayScheduling = {}
        }
        this.teamlist = response.rows;
        this.listSchedulingFn() // 整个驻点的排班
      });
    },
    cancel() {
      this.$emit('update:visible', false)
    },
    // 每月天数的具体信息
    getDaysOfWeek(year, month) {
      let week = ['日', '一', '二', '三', '四', '五', '六']
      let dayMonth = []
      let d = new Date(year, month, 0)
      let day = d.getDate();
      this.widthTable = day * 60 + 100
      let firstDayOfMonth = new Date(year, month - 1, 1)
      //该月第一天是周几?0表示周日，1表示周一...6表示周六
      let dayWeek = firstDayOfMonth.getDay()
      for (let i = 0; i < day; i++) {
        dayMonth.push({
          day: `${year}-${month}-${i + 1}`,
          week: week[dayWeek],
          dayName: i + 1
        })
        dayWeek++
        if (dayWeek > 6) {
          dayWeek = 0
        }
      }
      this.dayMonth = dayMonth
      this.getUserList() // 获取团队信息
    },
    // 当前月份
    newDate() {
      let date = new Date()
      let y = date.getFullYear()
      let m = date.getMonth() + 1
      m = m < 10 ? '0' + m : m
      return y + '-' + m
    },
    // 搜索月份变更
    monthThisFn() {
      let time_ = this.monthThis.split('-')
      this.getDaysOfWeek(time_[0], time_[1])
    }
  }
}
</script>

<style scoped>
.table-scheduling {
  border: 1px solid #ddd;
  overflow-x: auto;
  background: #fff;
}

.table-scheduling-header {
  /*display: flex;*/
  /*align-items: center;*/
  background: #f6f6f6;
  height: 50px;
  line-height: 50px;
  border-bottom: 1px solid #ddd;
  overflow-y: auto;
}

.table-scheduling-list {
  /*display: flex;*/
  /*align-items: center;*/
  border-bottom: 1px solid #ddd;
}

.table-scheduling-list:last-child {
  border: none;
}

.table-scheduling-time {
  overflow: hidden;
}

.table-scheduling-time-list {
  height: 50px;
  width: 100px;
  text-align: center;
  line-height: 50px;
  border-right: 1px solid #ddd;
  float: left;
}

.table-scheduling-time-list-td {
  /*flex: 1;*/
  width: 60px;
  height: 50px;
  line-height: 50px;
  border-right: 1px solid #ddd;
  text-align: center;
  float: left;
}

.table-scheduling-time-list-td:last-child {
  border: none;
}

.table-scheduling-time-list-td-day {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.table-scheduling-time-list-td-day span {
  display: block;
  line-height: 20px;
  text-align: center;
}

.table-scheduling-time-list-td-day .day {

}

.table-scheduling-time-list-td-day .week {

}

.scheduling-top {
  border-bottom: 1px solid #ddd;
  margin-bottom: 10px;
}

.scheduling-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.scheduling-header-name {
  margin-right: 10px;
}

.scheduling-header-list {
  display: flex;
}

.scheduling-header-list-line {
  margin-right: 10px;
  padding: 3px 10px;
  border-radius: 5px;
  color: #fff;
}

.scheduling-header-list-type {
  color: #333;
  background: #ddd;
}

.scheduling-top-time {
  margin-bottom: 10px;
  text-align: right;
}

.popover-body {
  width: 100%;
  height: 100%;
  position: relative;
}

.popover-title {
  height: 40px;
  text-align: center;
  line-height: 40px;
  font-weight: bold;
}

.popover-box-title-list {
  height: 40px;
  text-align: center;
  line-height: 40px;
  margin-bottom: 5px;
  color: #fff;
  cursor: pointer;
}

.popover-box-title-list:hover {
  text-decoration: underline;
}

.popover-box-rest {
  background: #f5f5f5;
  color: #333;
  cursor: pointer;
}

.popover-box-clear {
  background: #f5f5f5;
  color: #ed5565;
  cursor: pointer;
}

.popoverLine .button-scheduling {
  width: 60px;
  height: 50px;
  padding: 0;
  background: none;
  white-space: normal;
  cursor: pointer;
  display: block;
}

.popoverLine .button-scheduling:hover {
  background: #ddd;
}

.notdata {
  text-align: center;
  padding: 20px 0;
}
</style>
